<!--
 * @Author: krsea 965837746@qq.com
 * @Date: 2025-03-11 08:37:11
 * @LastEditors: krsea 965837746@qq.com
 * @LastEditTime: 2025-03-11 09:20:25
 * @FilePath: \vue3-code\2306\week4\1.非父子组件之间的通信.html
 * @Description: 
 * 
 * Copyright (c) 2025 by ${git_name_email}, All Rights Reserved. 
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>非父子组件之间的通信</title>
    <!-- 引入vue.js -->
    <script src="../js/vue.js"></script>
</head>

<body>
    <!-- 挂载点 -->
    <div id="app">
        <h2>组件A：向总线bus 上报事件</h2>
        <my-component-a></my-component-a>
        <h2>组件B：通过总线监听事件</h2>
        <my-component-b></my-component-b>
    </div>

    <!-- 使用javascript 脚本 -->
    <script type="text/javascript">
        var bus = new Vue(); // 创建一个总线
        Vue.component('my-component-a', { 
            template:`<div>
            <p>组件A</p>
            <hr>
            <button v-on:click="doClick">{{ counter }}</button>
        </div>`,
            data() {
                return {
                    counter: 0
                }
            },
            methods: {
                doClick() {
                    this.counter++;
                    // 向总线bus 上报事件 ( 事件名, 参数)
                    bus.$emit('btn-click', this.counter)
                }
            },
         });

        Vue.component('my-component-b', {
              template:`<div>
            <p>组件B</p>
            <hr>
            计数器: {{ counter }}
            <hr>
        </div>`, 
            data() {
                return {
                    counter: 0
                }
            },
            created() {
                // 监听总线bus 的事件  接收参数
                bus.$on('btn-click', (counter) => {
                    this.counter = counter;
                    // this.doChildClick();
                })

            },
        })
        var app = new Vue({
            el: '#app'
        })
    </script>
</body>

</html>